<?php

namespace app\company\controller\crisis_intervention\list;

use app\admin\service\InterfereExportService;
use app\BaseController;
use app\model\ConsultOfflineFactorScoreModel;
use app\model\ConsultOfflineResultModel;
use app\model\ConsultOnlineFactorScoreModel;
use app\model\ConsultOnlineResultModel;
use app\model\CrisisBehaviorModel;
use app\model\DepartmentModel;
use app\model\FollowUserModel;
use app\model\ProxyEvaluationResultModel;
use app\model\ProxyFactorScoreModel;
use app\model\RatingScaleFactorWarningModel;
use app\model\RatingScaleTypeModel;
use app\model\SelfEvaluationResultModel;
use app\model\SelfFactorScoreModel;
use app\model\TaskFactorScoreModel;
use app\model\TaskUserResultModel;
use app\model\UnitModel;
use app\model\UserModel;
use think\App;

class Follow extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 关注人群列表
     * @return bool|string
     */
    public function Index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'unit_id|单位ID'  =>  'require',
                'pageSize|每页显示数量' => 'require',
            ]);
            $where = [];
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['level'])) {
                $where[] = ['level', '=', $param['level']];
            }
            if (!empty($param['up_num'])) {
                $where[] = ['up_num', '=', $param['up_num']];
            }
            if (!empty($param['channel'])) {
                $where[] = ['channel', '=', $param['channel']];
            }
            if (!empty($param['operator_uid'])) {
                $where[] = ['operator_uid', '=', $param['operator_uid']];
            }
            if (!empty($param['department_id']) && !empty($param['name'])) {
                $UserModel = new UserModel();
                $uids = $UserModel->where([
                    ['name|username', 'like', '%' . $param['name'] . '%'],
                    ['department_id', '=', $param['department_id']],
                ])->column('id');
                if (count($uids) > 0) {
                    $where[] = ['uid', 'in', $uids];
                } else {
                    $where[] = ['id', '=', '-1'];
                }
            } else {
                if (!empty($param['name'])) {
                    $UserModel = new UserModel();
                    $uids = $UserModel->where('name|username', 'like', '%' . $param['name'] . '%')->column('id');
                    if (count($uids) > 0) {
                        $where[] = ['uid', 'in', $uids];
                    } else {
                        $where[] = ['id', '=', '-1'];
                    }
                }
                if (!empty($param['department_id'])) {
                    $UserModel = new UserModel();
                    $uids = $UserModel->where('department_id', '=', $param['department_id'])->column('id');
                    if (count($uids) > 0) {
                        $where[] = ['uid', 'in', $uids];
                    } else {
                        $where[] = ['id', '=', '-1'];
                    }
                }
            }
            if (!empty($param['uid'])) {
                $where[] = ['uid', '=', $param['uid']];
            }
            if (!empty($param['id'])) {
                $where[] = ['id', 'in', $param['id']];
            }
            $where[] = ['unit_id', '=', $param['unit_id']];
            $where[] = ['status', '=', 0];
            $FollowUserModel = new FollowUserModel();
            $query = $FollowUserModel->where($where);
            $data = $query->with([
                'operator',
                'user' => function ($query) {
                    $query->with([
                        'department' => function ($query) {
                            $query->with([
                                'departmentAdmins' => function ($query) {
                                    $query->with(['userName']);
                                }
                            ]);
                        },
                        'unitName']);
                }
            ])->order('id desc')->paginate($param['pageSize'])->toArray();
            $TaskUserResultModel = new TaskUserResultModel();
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $ConsultOnlineResultModel = new ConsultOnlineResultModel();
            $ConsultOfflineResultModel = new ConsultOfflineResultModel();
            foreach ($data['data'] as &$item) {
                $model = match ($item['channel']){
                    2, 7 => $TaskUserResultModel,
                    3, 8 => $SelfEvaluationResultModel,
                    5, 9 => $ConsultOnlineResultModel,
                    6, 10 => $ConsultOfflineResultModel,
                    default => false
                };
                if (!$model) continue;
                $result = $model->with([
                    'RatingScaleFactorWarningModel',
                    'RatingScale' => function ($query) {
                        $query->with(['ratingScaleTypeName']);
                    }
                ])->find($item['channel_id']);
                if (!$result) continue;
                $result = $result->toArray();
                $item['rating_scale_name'] = $result['rating_scale_name'];
                $item['warning_name'] = $result['warning_name'];
                $item['result_read_auth'] = $result['result_read_auth']??'';
                $item['total_score'] = $result['total_score'];
                $item['is_explain'] = $result['is_explain'];
                $item['rating_scale_type_name'] = $result['rating_scale_type_name'];
                $item['answer_role'] = $result['answer_role']??'';
            }
            $data['ids'] = $query->column('id');
            $UnitModel = new UnitModel();
            $data['unit_name'] = $UnitModel->where('id','=',$param['unit_id'])->value('name');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 批量导出关注人群
     * @return bool|string
     */
    public function FollowUserExport(): bool|string
    {
        try {
            $id = $this->request->param('id');
            if (!is_array($id)) throw new \Exception('参数错误！');
            $InterfereService = new InterfereExportService($this->app);
            return success($InterfereService->FollowUserExport($id));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 关注人群高级筛选
     * @return bool|string
     */
    public function FollowUser(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'unit_id|单位ID'  =>  'require',
            ]);
            $where = [];
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['department_id'])) {
                $UserModel = new UserModel();
                $uid = $UserModel->where('department_id', 'in', $param['department_id'])->column('id');
                if (count($uid)) {
                    $where[] = ['uid', 'in', $uid];
                } else {
                    $where[] = ['uid', '=', -1];
                }
            }
            if (!empty($param['level'])) {
                $where[] = ['level', 'in', $param['level']];
            }
            if (!empty($param['channel'])) {
                $where[] = ['channel', 'in', $param['channel']];
            }
            if (!empty($param['is_up'])) {
                if ($param['is_up'] == 1) {
                    $where[] = ['up_num', '>', 0];
                } else {
                    $where[] = ['up_num', '=', 0];
                }
            }
            $ResultWhere = [];
            if (!empty($param['factor_id']) && !empty($param['warning'])) {
                $RatingScaleFactorWarningModel = new RatingScaleFactorWarningModel();
                $warning_ids = [];
                foreach ($param['warning'] as $item) {
                    if (empty($item['mark_count'])) continue;
                    $warning_id = $RatingScaleFactorWarningModel->where([
                        ['rating_scale_id', '=', $item['rating_scale_id']],
                        ['mark_count', 'in', $item['mark_count']]
                    ])->column('id');
                    $warning_ids = array_merge($warning_ids, $warning_id);
                }
                $ResultWhere[] = ['factor_id', 'in', $param['factor_id']];
                if (count($warning_ids)) {
                    $ResultWhere[] = ['warning_id', 'in', $warning_ids];
                } else {
                    $ResultWhere[] = ['warning_id', '=', -1];
                }
            } else {
                if (!empty($param['factor_id'])) {
                    $ResultWhere[] = ['factor_id', 'in', $param['factor_id']];
                }
                if (!empty($param['warning'])) {
                    $RatingScaleFactorWarningModel = new RatingScaleFactorWarningModel();
                    $warning_ids = [];
                    foreach ($param['warning'] as $item) {
                        if (empty($item['mark_count'])) continue;
                        $warning_id = $RatingScaleFactorWarningModel->where([
                            ['rating_scale_id', 'in', $item['rating_scale_id']],
                            ['mark_count', 'in', $item['mark_count']]
                        ])->column('id');
                        $warning_ids = array_merge($warning_ids, $warning_id);
                    }
                    if (count($warning_ids)) {
                        $ResultWhere[] = ['warning_id', 'in', $warning_ids];
                    } else {
                        $ResultWhere[] = ['warning_id', '=', -1];
                    }
                }
            }
            $result_ids = [];
            if (count($ResultWhere) > 0) {
                $TaskFactorScoreModel = new TaskFactorScoreModel();
                $task_result_id = $TaskFactorScoreModel->where($ResultWhere)->column('result_id');
                $SelfFactorScoreModel = new SelfFactorScoreModel();
                $self_result_id = $SelfFactorScoreModel->where($ResultWhere)->column('result_id');
                $ProxyFactorScoreModel = new ProxyFactorScoreModel();
                $proxy_result_id = $ProxyFactorScoreModel->where($ResultWhere)->column('result_id');
                $ConsultOfflineFactorScoreModel = new ConsultOfflineFactorScoreModel();
                $offline_result_id = $ConsultOfflineFactorScoreModel->where($ResultWhere)->column('result_id');
                $ConsultOnlineFactorScoreModel = new ConsultOnlineFactorScoreModel();
                $online_result_id = $ConsultOnlineFactorScoreModel->where($ResultWhere)->column('result_id');
                $result_ids = array_merge($task_result_id, $self_result_id, $proxy_result_id, $offline_result_id, $online_result_id);
                $result_ids = array_unique($result_ids);
            }
            if (!empty($param['is_explain'])) {
                $TaskUserResultModel = new TaskUserResultModel();
                $SelfEvaluationResultModel = new SelfEvaluationResultModel();
                $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
                $ConsultOnlineResultModel = new ConsultOnlineResultModel();
                $ConsultOfflineResultModel = new ConsultOfflineResultModel();
                $ResultWhere = [];
                if ($param['is_explain'] == 1) {
                    $ResultWhere[] = ['is_explain', '=', 3];
                } else {
                    $ResultWhere[] = ['is_explain', '<', 3];
                }
                $task_result_id = $TaskUserResultModel->where($ResultWhere)->column('id');
                $self_result_id = $SelfEvaluationResultModel->where($ResultWhere)->column('id');
                $proxy_result_id = $ProxyEvaluationResultModel->where($ResultWhere)->column('id');
                $online_result_id = $ConsultOnlineResultModel->where($ResultWhere)->column('id');
                $offline_result_id = $ConsultOfflineResultModel->where($ResultWhere)->column('id');
                $result_id = array_merge($task_result_id, $self_result_id, $proxy_result_id, $online_result_id, $offline_result_id);
                $result_id = array_unique($result_id);
                if (count($result_ids)) {
                    $result_ids = array_intersect($result_ids, $result_id);
                } else {
                    $result_ids = $result_id;
                }
            }
            if (!empty($param['factor_id']) || !empty($param['warning']) || !empty($param['is_explain'])) {
                if (count($result_ids)) {
                    $result_ids = array_unique($result_ids);
                    $where[] = ['channel_id', 'in', $result_ids];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            $where[] = ['unit_id', '=', $param['id']];
            $where[] = ['status', '=', 0];
            $FollowUserModel = new FollowUserModel();
            $ids = $FollowUserModel->where($where)->column('id');
            if (empty($ids)) {
                $ids = [-1];
            }
            return success($ids);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}